package com.top.art.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.top.art.bo.ExaminationBO;
import com.top.art.constants.Status;
import com.top.art.entity.ExaminationInfo;
import com.top.art.entity.ExamineeInfo;
import com.top.art.entity.StudioInfo;
import com.top.art.exception.ArtException;
import com.top.art.mapper.ExaminationInfoMapper;
import com.top.art.service.IExaminationInfoService;
import com.top.art.service.IExamineeInfoService;
import com.top.art.service.IStudioInfoService;
import com.top.art.utils.GenerateCode;
import com.top.art.vo.ExaminationMessageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Clock;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

import static com.top.art.tool.Tool.notNullAndEmpty;

/**
 * <p>
 * 考场信息表 服务实现类
 * </p>
 *
 * @author hjh
 * @since 2020-10-06
 */
@Service
public class ExaminationInfoServiceImpl extends ServiceImpl<ExaminationInfoMapper, ExaminationInfo> implements IExaminationInfoService {

    @Autowired
    private IStudioInfoService studioInfoService;

    @Autowired
    private IExamineeInfoService examineeInfoService;

    @Autowired
    private IExaminationInfoService examinationInfoService;

    @Autowired
    private GenerateCode generateCode;

    @Override
    public List<ExaminationInfo> groupByareaCode(ExaminationBO bo) {
        /**
         * 1.先检查一下考场总容纳人数与考生人数是否匹配.
         * 2.两个队列进行排序,  画室队列按人数从大到小,  考场队列按人数从小到大.
         * 3.以画室队列为主循环, 按照步骤1指定的顺序, 记录考场编号.
         * 4.保存分配结果. [此时可考虑导出分配结果]
         */

        // 查询某地区，每个考场对应的可容纳人数
//        Map<String,Integer> map= new HashMap<>();
//        this.list(Wrappers.<ExaminationInfo>lambdaQuery().eq(ExaminationInfo::getExamArea,bo.getProviceCode()).eq(ExaminationInfo::getActivityStatus, Status.VALID)).
//                stream().collect(Collectors.groupingBy(ExaminationInfo::getExamCode)).forEach((s, examinationInfos) -> {
//                    for (ExaminationInfo info:examinationInfos){
//                        map.put(info.getExamCode(),info.getPeopleCount());
//                    }
//                }
//        );
        return this.list(Wrappers.<ExaminationInfo>lambdaQuery().eq(ExaminationInfo::getExamArea,bo.getProvinceCode()).eq(ExaminationInfo::getActivityStatus, Status.VALID)).
                stream().sorted(Comparator.comparing(ExaminationInfo::getPeopleCount).reversed()).collect(Collectors.toList());
    }

    @Override
    public boolean setExaminationInfo(ExaminationBO bo) {
        Assert.notNull(bo,"请求信息错误!");
        try {
            if(!bo.getMap().isEmpty()){
                bo.getMap().forEach((s, integer) -> {
                    ExaminationInfo info = new ExaminationInfo();
//                    info.setProvinceCode(bo.getProvinceCode());
                    info.setProvince(bo.getProviceName());
                    info.setExamCode(s);
                    info.setPeopleCount(integer);
                    this.save(info);
                });
            }
            // 考场分配：考生生成准考证，分配考场
            distribution(bo.getProvinceCode());
            return true;
        } catch (Exception e) {
//           throw new ArtException(500,"考场设置报错，请检查输入的信息是否正确");
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public ExaminationMessageVo distribution(String provinceCode) {
        List<ExamineeInfo> examineeInfoList = new ArrayList<>();
        Map<String,Integer> stringIntegerMap = new HashMap<>();
        examinationInfoService.list(Wrappers.<ExaminationInfo>lambdaQuery()
                .eq(notNullAndEmpty(provinceCode), ExaminationInfo::getExamArea,provinceCode)
                .eq(ExaminationInfo::getActivityStatus,Status.VALID)
                .orderByDesc(ExaminationInfo::getPeopleCount)).stream().forEach(examination -> {
            // 画室 可容纳50 人
            int num = examination.getPeopleCount();
            stringIntegerMap.put(examination.getExamCode(),examination.getPeopleCount());
            examineeInfoService.list(Wrappers.<ExamineeInfo>lambdaQuery()
                    .eq(notNullAndEmpty(examination.getExamCode()),ExamineeInfo::getStudioCode,examination.getExamCode())
                    .eq(ExamineeInfo::getActivityStatus,Status.VALID)).stream().forEach(examineeInfo -> {
                    examineeInfo.setAdmissionTicketCode(generateCode.getGenerateCode());
                    examineeInfo.setLastUpdateTime(LocalDateTime.now(Clock.system(ZoneId.of("Asia/Shanghai"))));
                    try {
                    Thread.sleep(1);
                    } catch (Exception e) {
                    e.printStackTrace();
                  }
                    examineeInfoList.add(examineeInfo);
            });
            stringIntegerMap.forEach((s, integer) -> {
                for(int i=0;i<integer;i++){
                    List<ExamineeInfo> infolist = new ArrayList<>();
                    ExamineeInfo entity = infolist.get(i);
                    entity.setExaminationRoomCode(s);
                    infolist.add(entity);
                    examineeInfoService.saveBatch(infolist);
                    examineeInfoList.removeAll(infolist);
                }
            });
            examineeInfoList.stream().forEach(examineeInfo -> {
                System.out.println(examination.toString());
            });

        });
        ExaminationMessageVo vo = new ExaminationMessageVo();
        vo.setList(examineeInfoList);
        return vo;
    }

}
//    List<ExamineeInfo> examineeInfoList = new ArrayList<>();
//            examineeInfoService.list(Wrappers.<ExamineeInfo>lambdaQuery().eq(notNullAndEmpty(examination.getExamCode()),ExamineeInfo::getStudioCode,examination.getExamCode()))
//        .stream().forEach(examineeInfo -> {
//        // XX 画室30人
//        //月日时分秒毫秒为准考证号
//        examineeInfo.setAdmissionTicketCode(generateCode.getGenerateCode());
//        examineeInfo.setLastUpdateTime(LocalDateTime.now(Clock.system(ZoneId.of("Asia/Shanghai"))));
//        try {
//        Thread.sleep(1);
//        } catch (Exception e) {
//        e.printStackTrace();
//        }
//        examineeInfoList.add(examineeInfo);
//        });
//        for(ExamineeInfo info:examineeInfoList){
//        info.setExaminationRoomCode(examination.getExamCode());
//        examineeInfoService.saveOrUpdate(info);
//        }